package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"questionnaire-gen/backend"
	"gopkg.in/mgo.v2/bson"
)

var (
)

func init() {

	/*
		s, c := backend.GetSessionColl("users")
		defer s.Close()
		newUser := &backend.User{}

		c.Find(bson.M{"Email":user.Email}).One(newUser)
	*/

}

/*
 */

func login(w http.ResponseWriter, r *http.Request, c *AppContext, rq *ReqContext) error {
	s, u := backend.GetColl(nil, backend.CUsers)
	s, o := backend.GetColl(s, backend.COrgs)
	defer s.Close()



	var user = &backend.User{}

	fmt.Println("logging in with user: " , user)

	err := json.NewDecoder(r.Body).Decode(user)
	if err != nil { // this error shouldn't be thrown in production
		http.Error(w, "invalid JSON user format", http.StatusInternalServerError)
		return err
	}

	//cachedUser, ok := backend.Cache["u_mail_"+user.Email].(*backend.User)
	fmt.Println("finding user by email : " , user.Email)
	cachedUser := &backend.User{}

	err = u.Find(bson.M{"email":user.Email}).One(cachedUser)

	if err != nil {
		fmt.Println(err)
		http.Error(w, "User not registered, please contact the site Admin", http.StatusInternalServerError)
		return nil
	}


	if user.Password != cachedUser.Password {
		//get the organization which the user is authorized to edit
/*
		orgs := make([]*backend.Org, 0)
		mapf := func (item interface{} ){
			v, ok := item.(*backend.Org)
			if ok && v.UserEmail == user.Email{
				orgs = append(orgs, v)
			}
		}

		findf := func(item interface{}) bool{
			v, ok := item.(*backend.Org)
			if ok && v.UserEmail == user.Email{
				return true
			}
			return false
		}

		userOrg, ok := find("org_", findf).(*backend.Org)

		*/
		userOrg := &backend.Org{}
		err = o.Find(bson.M{"useremail": user.Email }).One(userOrg)

		if err != nil || userOrg == nil {
			http.Error(w, "User not registered to an organization, please call admin to add you to your org", http.StatusInternalServerError)
			return err
		}

		if userOrg.Password != user.Password {
			http.Error(w, "Wrong password", http.StatusInternalServerError)
			return nil
		}
	}

	st, _ := c.store.Get(r, "user")
	st.Values["email"] = cachedUser.Email
	st.Save(r, w)
	json.NewEncoder(w).Encode(cachedUser)

	return err
}

func logout(w http.ResponseWriter, r *http.Request, c *AppContext, rc *ReqContext) error {
	s, _ := c.store.Get(r, "user")
	delete(s.Values, "email")
	s.Save(r, w)
	return nil
}

func auth(w http.ResponseWriter, r *http.Request, c *AppContext, rc *ReqContext) error {

	s, _ := c.store.Get(r, "user")
	email, ok := s.Values["email"]
	fmt.Println("user email from session: " , email)
	if !ok {
		//http.Error(w, "User not logged in",http.StatusInternalServerError)
		return nil
	}

	//user, ok := userCache[email.(string)]
	user, ok := backend.Cache["u_mail_"+email.(string)].(*backend.User)
	if !ok {
		fmt.Fprintln(w, "null")
		//http.Error(w, "User not cached",http.StatusInternalServerError)
		return nil
	}
	user = user
	user.Password = ""
	w.Header().Add("Content-Type", "application/json")
	err := json.NewEncoder(w).Encode(user)
	if err != nil {
		log.Fatal(err)
		//fmt.Fprint(w, "null")
	}
	return err
}
